const jwt = require('jsonwebtoken');
const config = require('../config/auth');
const User = require('../models/User');
const { errorResponse } = require('../utils/response');
const logger = require('../utils/logger');

// 验证用户是否登录
exports.auth = async (req, res, next) => {
  try {
    // 获取请求头中的token
    const authHeader = req.header('Authorization');
    if (!authHeader) {
      return errorResponse(res, '未授权，请登录', 401);
    }
    
    const token = authHeader.replace('Bearer ', '');
    
    // 验证token
    const decoded = jwt.verify(token, config.jwtSecret);
    
    // 查找用户
    const user = await User.findById(decoded.id).select('-password');
    if (!user) {
      return errorResponse(res, '用户不存在', 401);
    }
    
    // 检查用户状态
    if (user.status !== 'active') {
      return errorResponse(res, '账户已被禁用', 403);
    }

    // 将用户信息附加到请求对象
    req.user = user;
    next();
  } catch (error) {
    logger.error(`验证失败: ${error.message}`);
    return errorResponse(res, '验证失败，请重新登录', 401);
  }
};

// 检查是否为管理员权限
exports.admin = (req, res, next) => {
  if (req.user && req.user.role === 'admin') {
    next();
  } else {
    return errorResponse(res, '需要管理员权限', 403);
  }
};

// 检查是否为管理员或经理权限
exports.manager = (req, res, next) => {
  if (req.user && (req.user.role === 'admin' || req.user.role === 'manager')) {
    next();
  } else {
    return errorResponse(res, '需要管理员或经理权限', 403);
  }
}; 